<template>
    <div class="issue-dashboard">
      <div class="workspace-tree">
        <el-tree
          :data="workspaces"
          :props="defaultProps"
          @node-click="handleNodeClick"
          class="tree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span class="add-button" @click.stop="handleAddButtonClick(data)">
              <i class="el-icon-plus"></i>
            </span>
          </span>
        </el-tree>
        <el-dialog
          title="创建子空间"
          :visible.sync="dialogVisible"
          width="30%"
        >
          <el-form :model="newWorkspace" label-width="120px">
            <el-form-item label="名称">
              <el-input v-model="newWorkspace.name"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="newWorkspace.description"></el-input>
            </el-form-item>
            <el-form-item label="主R">
              <el-input v-model="newWorkspace.projectLeader"></el-input>
            </el-form-item>
            <el-form-item label="项目成员">
              <el-input v-model="newWorkspace.teamMembers"></el-input>
            </el-form-item>
            <el-form-item label="需求名">
              <el-input v-model="newWorkspace.requirementName"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="createSubWorkspace">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <div class="issue-list">
        <el-card v-if="filteredIssues.length === 0" class="issue-card no-data-card">
          <div class="no-data">
            <el-empty description="暂无数据"></el-empty>
          </div>
        </el-card>
        <el-card v-for="issue in filteredIssues" :key="issue.id" class="issue-card">
          <div slot="header" class="clearfix">
            <span class="issue-title">{{ issue.title }}</span>
            <el-tag :type="issue.priority | priorityType" class="issue-priority">{{ issue.priority }}</el-tag>
          </div>
          <div class="issue-details">
            <p><strong>指派人:</strong> {{ issue.assigner }}</p>
            <p><strong>发起时间:</strong> {{ issue.createdTime | formatTime }}</p>
            <p><strong>缺陷等级:</strong> {{ issue.severity }}</p>
          </div>
          <el-divider></el-divider>
          <div class="issue-actions">
            <el-select v-model="issue.status" placeholder="请选择操作" @change="handleStatusChange(issue)">
              <el-option
                v-for="item in getStatusOptions(issue)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select v-if="issue.status === 'resolved'" v-model="issue.issueType" placeholder="请选择缺陷类型" @change="handleIssueTypeChange(issue)">
              <el-option
                v-for="item in issueTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select v-if="issue.status === 'postponed'" v-model="issue.postponeReason" placeholder="请选择延时原因" @change="handlePostponeReasonChange(issue)">
              <el-option
                v-for="item in postponeReasons"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </el-card>
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    name: 'IssueDashboard',
    data() {
      return {
        workspaces: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        issues: [],
        selectedWorkspace: null,
        statusOptions: [
          { value: 'open', label: '待处理' },
          { value: 'inProgress', label: '处理中' },
          { value: 'resolved', label: '已解决' },
          { value: 'postponed', label: '延时' }
        ],
        issueTypes: [
          { value: 'notADefect', label: '不是缺陷' },
          { value: 'technicalIssue', label: '技术问题' },
          { value: 'logicalDesignIssue', label: '逻辑设计问题' },
          { value: 'requirementIssue', label: '需求问题' },
          { value: 'other', label: '其他' }
        ],
        postponeReasons: [
          { value: 'waitingForDependency', label: '等待依赖项' },
          { value: 'waitingForResource', label: '等待资源' },
          { value: 'other', label: '其他' }
        ],
        dialogVisible: false,
        newWorkspace: {
          name: '',
          description: '',
          projectLeader: '',
          teamMembers: '',
          requirementName: ''
        },
        selectedNode: null
      };
    },
    computed: {
      filteredIssues() {
        if (!this.selectedWorkspace) {
          return this.issues;
        }
        return this.issues.filter(issue => issue.workspace === this.selectedWorkspace);
      }
    },
    filters: {
      priorityType(priority) {
        switch (priority) {
          case '高': return 'danger';
          case '中': return 'warning';
          case '低': return 'info';
          default: return '';
        }
      },
      formatTime(time) {
        const date = new Date(time);
        return date.toLocaleString();
      }
    },
    methods: {
      handleNodeClick(data) {
        this.selectedWorkspace = data.name;
        this.issues = this.transformIssueData(data.problemDOList || []);
      },
      handleAddButtonClick(data) {
        this.selectedNode = data;
        this.dialogVisible = true;
      },
      getStatusOptions(issue) {
        if (issue.status === 'inProgress') {
          return this.statusOptions.filter(option => option.value !== 'open');
        } else {
          return this.statusOptions;
        }
      },
      handleStatusChange(issue) {
        if (issue.status === 'resolved') {
          issue.issueType = '';
        } else if (issue.status === 'postponed') {
          issue.postponeReason = '';
        }
      },
      handleIssueTypeChange(issue) {
        // 处理缺陷类型选择
        console.log(`Issue ${issue.id} 缺陷类型: ${issue.issueType}`);
      },
      handlePostponeReasonChange(issue) {
        // 处理延时原因选择
        console.log(`Issue ${issue.id} 延时原因: ${issue.postponeReason}`);
      },
      fetchWorkspaceTree() {
        axios.get('/api/system/getspaceTree')
          .then(response => {
            if (response.data.code === 200) {
              this.workspaces = this.transformWorkspaceData(response.data.data);
            } else {
              this.$message.error('获取工作空间树失败');
            }
          })
          .catch(error => {
            console.error('获取工作空间树失败', error);
            this.$message.error('获取工作空间树失败');
          });
      },
      transformWorkspaceData(data) {
        const transform = (node) => {
          const transformedNode = {
            id: node.id,
            name: node.name,
            description: node.description,
            requirementName: node.requirementName,
            requirementId: node.requirementId,
            projectLeader: node.projectLeader,
            teamMembers: node.teamMembers,
            createdAt: node.createdAt,
            updatedAt: node.updatedAt,
            isparent: node.isparent,
            parent: node.parent,
            problemDOList: node.problemDOList || []
          };
          if (node.children && node.children.length > 0) {
            transformedNode.children = node.children.map(child => transform(child));
          }
          return transformedNode;
        };
        return [transform(data)];
      },
      transformIssueData(problemDOList) {
        return problemDOList.map(problem => ({
          id: problem.id,
          title: problem.description,
          assigner: problem.projectLeader,
          createdTime: problem.createtime,
          priority: problem.urgency,
          severity: problem.state === 0 ? '低' : (problem.state === 1 ? '中' : '高'),
          status: problem.state === 0 ? 'open' : (problem.state === 1 ? 'inProgress' : 'resolved'),
          workspace: this.selectedWorkspace,
          issueType: '',
          postponeReason: ''
        }));
      },
      createSubWorkspace() {
        if (!this.newWorkspace.name || !this.newWorkspace.description || !this.newWorkspace.projectLeader || !this.newWorkspace.teamMembers || !this.newWorkspace.requirementName) {
          this.$message.warning('请填写完整信息');
          return;
        }
        const newSubWorkspace = {
          name: this.newWorkspace.name,
          description: this.newWorkspace.description,
          projectLeader: this.newWorkspace.projectLeader,
          teamMembers: this.newWorkspace.teamMembers,
          requirementName: this.newWorkspace.requirementName,
          parent: this.selectedNode.id
        };
        axios.post('/api/system/createSubWorkspace', newSubWorkspace)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('创建子空间成功');
              this.dialogVisible = false;
              this.fetchWorkspaceTree();
            } else {
              this.$message.error('创建子空间失败');
            }
          })
          .catch(error => {
            console.error('创建子空间失败', error);
            this.$message.error('创建子空间失败');
          });
      }
    },
    created() {
      this.fetchWorkspaceTree();
    }
  };
  </script>
  
  <style scoped>
  .issue-dashboard {
    display: flex;
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    color: #2c3e50;
    padding: 20px;
  }
  
  .workspace-tree {
    width: 250px;
    margin-right: 20px;
  }
  
  .tree {
    background-color: #f5f5f5;
    border-radius: 10px;
    padding: 10px;
  }
  
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  
  .add-button {
    cursor: pointer;
    color: #409EFF;
  }
  
  .issue-list {
    flex: 1;
  }
  
  .issue-card {
    margin-bottom: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s;
  }
  
  .issue-card:hover {
    transform: translateY(-5px);
  }
  
  .issue-title {
    font-size: 1.2em;
    font-weight: bold;
  }
  
  .issue-priority {
    float: right;
  }
  
  .issue-details {
    margin-bottom: 20px;
  }
  
  .issue-actions {
    display: flex;
    justify-content: flex-end;
  }
  
  .el-select {
    margin-left: 10px;
  }
  
  .no-data-card {
    text-align: center;
    color: #909399;
  }
  
  .no-data {
    margin-top: 20px;
  }
  </style>
  